package dragon

import (
	"fmt"
	"http"
	"json"
	"template"
	"os"
	"strconv"
	"math"

	"appengine"
	"appengine/urlfetch"
)

const albumsFeed = `http://picasaweb.google.com/data/feed/api/user/%s?alt=%s&v=%s&fields=%s&max-results=%d&start-index=%d`
const albumscountFeed = `http://picasaweb.google.com/data/feed/api/user/%s?alt=%s&v=%s&fields=%s`

type album struct {
	Title string
	Id string
	Thumb string
}

func handleAlbums(w http.ResponseWriter, r *http.Request) {
	const pagelenPath = len(albumspageURL)
	const limit = 12
	const fields = "entry(media:group(media:title,media:thumbnail),gphoto:id)"
	const fieldscount = "entry()"
	var page int
	var err os.Error

	if !isAllDigits(r.URL.Path[pagelenPath:]) {
		http.Redirect(w, r, albumspageURL+"1", http.StatusFound)
		return
	}
	page, err = strconv.Atoi(r.URL.Path[pagelenPath:])
	if err != nil {
		http.Redirect(w, r, albumspageURL+"1", http.StatusFound)
		return
	}

	c := appengine.NewContext(r)
	client := urlfetch.Client(c)

	offset := ((page-1) * limit)+1
	tmpURL := fmt.Sprintf(albumsFeed, user, method, apiver, fields, limit, offset)
	resp, _ := client.Get(tmpURL)

	a := make([]album, limit)
	var d, dcount data

	dec := json.NewDecoder(resp.Body)
	dec.Decode(&d)
	resp.Body.Close()

	if len(d.Feed.Entry) < 1 {
		http.Redirect(w, r, albumspageURL+"1", http.StatusFound)
		return
	}

	tmpURL = fmt.Sprintf(albumscountFeed, user, method, apiver, fieldscount)
	resp, _ = client.Get(tmpURL)

	dec = json.NewDecoder(resp.Body)
	dec.Decode(&dcount)
	resp.Body.Close()

	a = getAlbums(&d, a)

	funcs := template.FuncMap{
		"selector": selector,
	}
	mapa := map[string]interface{} {
		"Entries": a,
		"Site": count(c, r, w),
		"Mapa": map[string]interface{} {
			"Pages": int(math.Ceil(float64(len(dcount.Feed.Entry))/limit)),
			"Page": page,
		},
	}

	ts := new(template.Set)
	troot, _ := template.New("root").
		Funcs(template.FuncMap{
			"date": stuffDate,
		}).
		ParseFile("templates/root.html")
	tcontent, _ := template.New("content").Funcs(funcs).
		ParseFile("templates/albums.html")
	ts.Add(troot, tcontent)
	ts.Execute(w, "root", mapa)
}

func getAlbums(d *data, a []album) []album {
	var k int
	for k = range d.Feed.Entry {
		if k+1 >= cap(a) {
			na := make([]album, k*2)
			copy(na, a)
			a = na
		} 
		var tmp interface{}

		tmp = d.Feed.Entry[k]["media$group"]
		a[k].Title = tmp.(map[string]interface{})["media$title"].(
				map[string]interface{})["$t"].(string)

		tmp = d.Feed.Entry[k]["gphoto$id"]
		a[k].Id = tmp.(map[string]interface{})["$t"].(string)

		tmp = d.Feed.Entry[k]["media$group"]
		a[k].Thumb = tmp.(map[string]interface{})["media$thumbnail"].(
				[]interface{})[0].(
				map[string]interface{})["url"].(string)
	}
	a = a[0:k+1]

	return a
}
